package com.ojoin.trade.t0loan_core.web.controller;


import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.ojoin.trade.common.constdef.IConstDef;
import com.ojoin.trade.common.exception.BusinessException;
import com.ojoin.trade.common.utils.CommonUtils;
import com.ojoin.trade.common.utils.DownloadUtils;
import com.ojoin.trade.common.utils.FileUploadUtils;
import com.ojoin.trade.common.utils.LogUtils;
import com.ojoin.trade.common.web.controller.BaseControllerImpl;
import com.ojoin.trade.common.web.domain.Result;
import com.ojoin.trade.common.web.domain.SessionUser;
import com.ojoin.trade.common.web.domain.Result.Status;
import com.ojoin.trade.common.web.service.BaseService;
import com.ojoin.trade.common_core.utils.TradeUtils;
import com.ojoin.trade.common_core.web.domain.MerchantUserInfo;
import com.ojoin.trade.common_core.web.service.impl.DataVersionValidationService;
import com.ojoin.trade.t0loan_core.web.domain.T0LoanCheckAccountInfoVO;
import com.ojoin.trade.t0loan_core.web.domain.T0LoanTransanctionLogInfoVO;
import com.ojoin.trade.t0loan_core.web.domain.TbIntentUser;
import com.ojoin.trade.t0loan_core.web.domain.TbT0LoanFinalApplication;
import com.ojoin.trade.t0loan_core.web.domain.TbT0LoanLiveApplication;
import com.ojoin.trade.t0loan_core.web.domain.TbT0LoanLiveInfoVO;
import com.ojoin.trade.t0loan_core.web.service.IntentUserBaseService;
import com.ojoin.trade.t0loan_core.web.service.T0LoanFinalBaseService;
import com.ojoin.trade.t0loan_core.web.service.T0LoanLiveBaseService;
import com.ojoin.trade.t0loan_core.web.service.T0LoanTransanctionLogBaseService;

@Controller
@RequestMapping("/t0loan")
public class T0LoanLiveApplicationController extends BaseControllerImpl<TbT0LoanLiveApplication>{
	
	private Logger log=LoggerFactory.getLogger(T0LoanLiveApplicationController.class);
	
	@Autowired
	private DataVersionValidationService validateService;
	
	public DataVersionValidationService getValidateService() {
		return validateService;
	}
	
	@Autowired
	private T0LoanLiveBaseService liveservice;

	public T0LoanLiveBaseService getLiveservice() {
		return liveservice;
	}

	@Autowired
	private IntentUserBaseService intentuserService;

	public IntentUserBaseService getIntentuserService() {
		return intentuserService;
	}

	
	@Autowired
	private T0LoanFinalBaseService finalservice;

	public T0LoanFinalBaseService getFinalservice() {
		return finalservice;
	}
	
	@Autowired
	private T0LoanTransanctionLogBaseService transservice;

	public T0LoanTransanctionLogBaseService getTransservice() {
		return transservice;
	}
	
	@Autowired
	private IntentUserBaseService intentUserService;

	public IntentUserBaseService getIntentUserService() {
		return intentUserService;
	}
	
	@ResponseBody
	@RequestMapping(value = "/insertliveinfo", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
	public Result insertLiveInfo(HttpServletRequest request) {
		try {
              int joinuserid=CommonUtils.getSessionUser(request).getId();

			int liveid = getLiveservice().insertT0LoanLiveInfo(joinuserid);
             return new Result(Status.OK, liveid);
		} catch (Exception e) {
			log.error("九盈用户id新增T+0贷款申请记录报错", e);
			if (e instanceof BusinessException)
				return new Result(Status.ERROR, e.getMessage());
			
			return new Result(Status.ERROR, "九盈用户id新增T+0贷款申请记录报错，请重试");
		}
	}
	
	@ResponseBody
	@RequestMapping(value = "/queryliveinfo", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public Result queryLiveInfo(HttpServletRequest request) {
		int joinuserid=CommonUtils.getSessionUser(request).getId();
		try {
			TbT0LoanLiveApplication livevo = getLiveservice().queryNewlyT0LoanLiveInfoByJoinUserID(joinuserid);
             return new Result(Status.OK, livevo);
		} catch (Exception e) {
			log.error("根据九盈用户id查询用户的最近一次T+0贷款申请记录报错", e);
			return new Result(Status.ERROR, "根据九盈用户id查询用户的最近一次T+0贷款申请记录报错，请重试");
		}
	}
	
	@ResponseBody
	@RequestMapping(value = "/queryTerminateInfo", method = RequestMethod.GET)
	public Result queryTerminateInfo(HttpServletRequest request) {
		SessionUser user = CommonUtils.getSessionUser(request);
		MerchantUserInfo merUser=TradeUtils.getMerchUser(request);
		int joinuserid=user.getId();
		try {
			TbT0LoanLiveApplication livevo = getLiveservice().queryNewlyT0LoanLiveInfoByJoinUserID(joinuserid);
            
			String fileName=livevo.getContractfilepath();
			fileName=fileName.substring(fileName.lastIndexOf(File.separator)+1);
		    fileName=fileName.substring(0,fileName.indexOf('.'));
		    String contractNO=fileName.substring(fileName.lastIndexOf('_')+1);
			
			Map<String,String> ret=new HashMap<String,String>();
            ret.put("contractNO",contractNO);
            ret.put("mchName",merUser.getMchName());
            
			return new Result(Status.OK, ret);
		} catch (Exception e) {
			log.error("根据九盈用户id查询用户的最近一次T+0贷款申请记录报错", e);
			return new Result(Status.ERROR, "根据九盈用户id查询用户的最近一次T+0贷款申请记录报错，请重试");
		}
	}
	
	
	@ResponseBody
	@RequestMapping(value = "/queryfinalinfo", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
	public Result queryFinalInfo(HttpServletRequest request) {
		int joinuserid=CommonUtils.getSessionUser(request).getId();
		try {
			TbT0LoanFinalApplication finalvo = getFinalservice().queryTxLoanFinalInfoByJoinUserID(joinuserid);
             return new Result(Status.OK, finalvo);
		} catch (Exception e) {
			log.error("根据九盈用户id查询用户的T+0贷款信息记录报错", e);
			if (e instanceof BusinessException)
				return new Result(Status.ERROR, e.getMessage());
			
			return new Result(Status.ERROR, "根据九盈用户id查询用户的T+0贷款信息记录报错，请重试");
		}
	}
	
	
	@ResponseBody
	@RequestMapping(value = "/queryjoinuserbalance", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public Result queryJoinuserBalance(HttpServletRequest request,Pageable page) {
		String mhtNo = CommonUtils.getSessionUser(request).getMhtNo();
		try {
			List<T0LoanCheckAccountInfoVO> balanceInfoList = getTransservice().queryT0LoanBalanceInfoListByDebtorMhtno(mhtNo,page);
             return new Result(Status.OK, balanceInfoList);
		} catch (Exception e) {
			log.error("查询指定商户的实时T+0贷款负债信息列表报错", e);
			if (e instanceof BusinessException)
				return new Result(Status.ERROR, e.getMessage());
			
			return new Result(Status.ERROR, "查询指定商户的实时T+0贷款负债信息列表报错，请重试");
		}
	}
	
	@ResponseBody
	@RequestMapping(value = "/queryLiveInfoByStatus", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
	public Result queryLiveInfoByStatus(@RequestBody String loanstatus, Pageable page) {
		if(StringUtils.isEmpty(loanstatus)) {
			return new Result(Status.ERROR, "审核状态为空，请检查.");
		}
		try {
			List<TbT0LoanLiveInfoVO> livelist = getLiveservice().queryAllT0LoanLiveInfoByStatus(CommonUtils.getInt(loanstatus), page);
             return new Result(Status.OK, livelist);
		} catch (Exception e) {
			log.error("查询状态为" + loanstatus + "的T+0贷款申请记录报错", e);
			if (e instanceof BusinessException)
				return new Result(Status.ERROR, e.getMessage());
			
			return new Result(Status.ERROR, "查询状态为" + loanstatus + "的T+0贷款申请记录报错，请重试");
		}
	}
	
	@ResponseBody
	@RequestMapping(value = "/queryT0LoanTransanctionLogInfoListByDebtorMhtNo", method = RequestMethod.GET)
	public Result queryT0LoanTransanctionLogInfoListByDebtorMhtNo(HttpServletRequest request,Pageable page) {
		String mhtNo = TradeUtils.getMhtNo(request);
		Map<String,String> param=new HashMap<String,String>();
		param.put("userIdOfIPayNowOfDebtor",mhtNo);

		try {
			List<T0LoanTransanctionLogInfoVO> livelist = getTransservice().queryT0LoanTransanctionLogInfoListByDebtorMhtNo(param,page);
             return new Result(Status.OK, livelist);
		} catch (Exception e) {
			log.error("查询指定债务人：" + mhtNo + "的贷款历史记录列表报错", e);
			if (e instanceof BusinessException)
				return new Result(Status.ERROR, e.getMessage());
			
			return new Result(Status.ERROR, "查询指定债务人：" + mhtNo + "的贷款历史记录列表报错，请重试");
		}
	}

	
	/**
     * @param request
     * @param files
     * @return
     */
	@ResponseBody
	@RequestMapping(value = "/uploadT0LoanUserCommitFileByLiveID", method = RequestMethod.POST)
	public Result uploadT0LoanUserCommitFileByLiveID(
            HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "contractfile", required = false) MultipartFile file) {

		if (null == file) {
			return new Result(Status.ERROR, "没有文件！");
		}
		int joinuserid=CommonUtils.getSessionUser(request).getId();
		
		String filename = file.getOriginalFilename();
		long size = file.getSize();

		try {
			String storeDir=FileUploadUtils.getDefaultBaseDir()+File.separator+IConstDef.contractUserFileDir;
			String url = FileUploadUtils.upload(request, storeDir, file,
					FileUploadUtils.DEFAULT_ALLOWED_EXTENSION, FileUploadUtils.defaultMaxSize, false);
			
			String filePath=IConstDef.contractUserFileDir+File.separator+FileUploadUtils.getFileNameFromPath(url);
			TbT0LoanLiveApplication livevo=getLiveservice().queryNewlyT0LoanLiveInfoByJoinUserID(joinuserid);
			if (livevo == null || livevo.getId() == 0){
				return new Result(Status.ERROR, "贷款申请id为空，请检查.");
		   }
			int liveId=livevo.getId();
			getLiveservice().uploadT0LoanUserCommitFileByLiveID(liveId, filePath);
		} catch (IOException e) {
			 LogUtils.info(log, "file upload error");
	          LogUtils.error(log, e);
			return new Result(Status.ERROR, filename + "文件错误!");
		} catch (FileUploadBase.FileSizeLimitExceededException e) {
			return new Result(Status.ERROR, filename + "文件过大，" + size);
		} catch (BusinessException e) {
			e.printStackTrace();
			log.error("上传用户盖章后的账户变更申请表，修改T+0贷款申请记录的状态为4报错", e);
			return new Result(Status.ERROR, "上传用户盖章后的账户变更申请表，修改T+0贷款申请记录的状态为4报错，请重试");
		}
		
		return new Result(Status.OK, filename+"文件上传成功！");
	}
    
	@ResponseBody
	@RequestMapping(value = "/queryT0LoanLiveContractFileByJoinuserid", method = RequestMethod.GET)
	public void queryT0LoanLiveContractFileByJoinuserid(
			HttpServletRequest request,
			HttpServletResponse response,String fileType ) {
		Integer joinuserid = CommonUtils.getSessionUser(request).getId();
		 
		try {
			 String[] filepath = getLiveservice().queryT0LoanLiveContractFileByJoinuserid(joinuserid);
			 if (filepath == null || filepath.length == 0)
				 log.error("九盈用户" + joinuserid + "申请T+0贷款记录的保理合同和账户变更申请表文件路径为空，请检查.");
			 
             if("CONTRACTFILE".equals(fileType)){
			 DownloadUtils.download(request, response, FileUploadUtils.getDefaultBaseDir()+File.separator+filepath[0], IConstDef.DOWNLOAD_CONTRACTFILE);
			 log.info("用户id{} 下载{}",new String[]{String.valueOf(joinuserid),IConstDef.DOWNLOAD_CONTRACTFILE});
             }
             if("ACCCHANGEAPPLY".equals(fileType)){
			 DownloadUtils.download(request, response, FileUploadUtils.getDefaultBaseDir()+File.separator+filepath[1], IConstDef.DOWNLOAD_ACCCHANGEAPPLY);
			 log.info("用户id{} 下载{}",new String[]{String.valueOf(joinuserid),IConstDef.DOWNLOAD_ACCCHANGEAPPLY});
             }
 
		} catch (Exception e) {
			log.error("查询指定九盈用户" + joinuserid + "申请T+0贷款记录状态为3的信息，获取生成的保理合同和账户变更申请表报错", e);
		}
	}
	
	 
	

	@ResponseBody
	@RequestMapping(value = "/addIntentUser", method = RequestMethod.POST)
	public Result addIntentUser(HttpServletRequest request, 
			String username, String city, String mobile) {
		if (StringUtils.isEmpty(username)) {
			return new Result(Status.ERROR, "用户名为空，请检查.");
		}
		if (StringUtils.isEmpty(city)) {
			return new Result(Status.ERROR, "城市为空，请检查.");
		}
		if (StringUtils.isEmpty(mobile)) {
			return new Result(Status.ERROR, "手机号为空，请检查.");
		}
		
		try {
			TbIntentUser intentuservo = new TbIntentUser();
			intentuservo.setMhtno(username);
			intentuservo.setCity(city);
			intentuservo.setMobile(mobile);
			intentuservo.setContactflag("0");
			getIntentuserService().insert(intentuservo);
             return new Result(Status.OK, intentuservo.getId());
		} catch (Exception e) {
			log.error("新增意向合作商户报错", e);
			if (e instanceof BusinessException)
				return new Result(Status.ERROR, e.getMessage());
			
			return new Result(Status.ERROR, "新增意向合作商户报错，请重试");
		}
	}
	
	@ResponseBody
	@RequestMapping(value = "/updateLiveInfoStatusToTerminate", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
	public Result updateLiveInfoStatusToTerminate(HttpServletRequest request) {
		Integer joinuserid = CommonUtils.getSessionUser(request).getId();
		TbT0LoanLiveApplication livevo=getLiveservice().queryNewlyT0LoanLiveInfoByJoinUserID(joinuserid);
		if (livevo == null || livevo.getId() == 0){
			return new Result(Status.ERROR, "贷款申请id为空，请检查.");
	    }
		int liveid=livevo.getId();
		try {
			getLiveservice().updateT0LoanLiveInfoByLiveIDsAndStatus(
					new int[] { liveid },
					IConstDef.LOANLIVETYPE_STOPAPPLY);
			return new Result(Status.OK, "更新成功");
		} catch (Exception e) {
			log.error("更新T+0贷款申请记录liveid->" + liveid + " loanstatus->" + IConstDef.LOANLIVETYPE_STOPAPPLY + "状态报错", e);
			if (e instanceof BusinessException)
				return new Result(Status.ERROR, e.getMessage());
			
			return new Result(Status.ERROR, "您申请终止合作失败!");
		}
	}
	
	@Override
	protected BaseService<TbT0LoanLiveApplication> getBaseService() {
		return null;
	}
}
